package com.hejun.securitywebsoceket.controller;

import com.hejun.securitywebsoceket.doMian.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@Controller
public class MessageController {

    @Autowired
    SimpMessagingTemplate messagingTemplate;

    @Autowired
    SessionRegistry  sessionRegistry;

    //广播消息队列，展示所有用户集
    @MessageMapping("/sendAll")
    public void sendAll(String message){
        System.out.println(message);
        List<Object> list = sessionRegistry.getAllPrincipals();//获取所有登录用户对象集合
        List<String> users=new ArrayList<>();//只需登录用户名称字符串集合
        for (Object o : list) {
            User u= (User) o;
            users.add(u.getUsername());
        }
        //发送消息目标地址为/topic/receive，所有订阅了/topic/receiveAll的客户端将收到此消息（广播）
        // 以/topic为前缀的代表广播
        //将所有登录用户的信息广播给全体客户端
        messagingTemplate.convertAndSend("/topic/receiveAll",users);
    }


    //获取当前用户
    @GetMapping("/getCurrentUser")
    @ResponseBody
    public String getCurrentUser(Principal principal){
        return principal.getName();
    }

    //点对点发送消息
    @MessageMapping("/sendTo")
    public void sendTo (Principal principal, Message message){
        message.setFrom(principal.getName());
        messagingTemplate.convertAndSendToUser(message.getTo(),"/queue/receiveOne",message);
        //如果有需要，也可同时发一份消息给自己
        messagingTemplate.convertAndSendToUser(message.getFrom(),"/queue/receiveOne",message);
    }

    @GetMapping("/chatOne")
    public String toIndex(){
        return "chatOne";
    }
}
